package com.yz.jdd.module.cashier.result;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.yunzong.permissions.Permission;
import com.yunzong.permissions.XXPermissions;
import com.yz.jdd.R;
import com.yz.jdd.base.activity.BaseActivity;
import com.yz.jdd.base.entity.Response_Base;
import com.yz.jdd.base.event.Events;
import com.yz.jdd.base.event.RxBus;
import com.yz.jdd.base.utils.BaseConfigs;
import com.yz.jdd.base.utils.LogUtils;
import com.yz.jdd.base.utils.PayConfig;
import com.yz.jdd.base.utils.PreferencesUtils;
import com.yz.jdd.base.utils.Tools;
import com.yz.jdd.module.cashier.CashierActivity;
import com.yz.jdd.network.ApiCallback;
import com.yz.jdd.network.NetWorkRequset;
import com.yz.jdd.network.request.Request_CloseOrder;
import com.yz.jdd.network.request.Request_Pay;
import com.yz.jdd.network.response.Response_Pay;
import com.yz.jdd.voice.OrderVoice;
import com.yz.jdd.voice.SpeechUtilOffline;

/**
 * 收款--关单界面
 * xiongzhuang
 * 2018-09-27
 */
public class CloseOrderActivity extends BaseActivity implements View.OnClickListener {

    private ImageView back_nav;//返回
    private TextView title_nav;//
    private TextView right_nav;//详情
    private ImageView iv_head;//顶部图片
    private TextView tv_main_message;//主要提示语
    private TextView tv_hint;//提示
    private Button btn_receipt;//重试或继续收款
    private Request_Pay request_pay;
    private static String FAIL_MESSAGE_RESET = "关闭订单失败，请重试";
    private static String FAIL_MESSAGE = "收款结果未知";
    private static String FAIL_MESSAGE_HINT = "请确认手机端支付结果，系统将在1天后自动更新订单状态";
    private static String FAIL_CLOSE_SUCCESS_MESSAGE = "收款失败";
    private static String SUCCESS_MESSAGE = "顾客已付款，无法关闭";
    private static String SUCCESS_MESSAGE_HINT = "如需查看请至订单详情";
    private boolean reset = false;//是否重试过
    private String str_voice_type;//支付类型
    String verifyCode;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_close_order);
        findViewById();
        initData();
    }

    private void findViewById() {
        back_nav =  findViewById(R.id.back_nav);
        back_nav.setVisibility(View.GONE);
        title_nav = (TextView) findViewById(R.id.title_nav);
        title_nav.setText("支付结果");
        right_nav = (TextView) findViewById(R.id.right_nav);
        right_nav.setText("完成");
        right_nav.setVisibility(View.VISIBLE);
        right_nav.setOnClickListener(this);
        iv_head = (ImageView) findViewById(R.id.iv_head);
        tv_main_message = (TextView) findViewById(R.id.tv_main_message);
        tv_hint = (TextView) findViewById(R.id.tv_hint);
        btn_receipt = (Button) findViewById(R.id.btn_receipt);
        btn_receipt.setOnClickListener(this);
        back_nav.setOnClickListener(this);

    }

    private void initData() {
        Intent intent = getIntent();
        request_pay = (Request_Pay) intent.getSerializableExtra("request_pay");
        verifyCode = intent.getStringExtra("verifyCode");
        request_pay.getOrderId();
        request_pay.getClientOrderId();
        // closeOrder();
        setData();
    }

    /**
     * 关单请求
     */
    private void closeOrder() {
        Request_CloseOrder request_closeOrdery = new Request_CloseOrder();
        request_closeOrdery.clientOrderId = request_pay.getClientOrderId();
        request_closeOrdery.orderId = request_pay.getOrderId();
        showLoadingNoCancelable("关单中，请稍后......");
        NetWorkRequset.closeOrder(request_closeOrdery, new ApiCallback() {
            @Override
            public void onSuccess(Response_Base response_baseModel) {
                dismissLoading();
                setData("1", response_baseModel);
            }

            @Override
            public void onNeedLogin(String msg) {
                dismissLoading();
            }

            @Override
            public void onFail(Response_Base response_baseModel) {
                dismissLoading();
                setData(response_baseModel.getCode(), response_baseModel);
            }
        });
    }

    public void setData() {
        btn_receipt.setVisibility(View.VISIBLE);
        iv_head.setImageResource(R.mipmap.casher_failure);
        iv_head.setVisibility(View.VISIBLE);

        tv_main_message.setText("等待交易结果超时");
        tv_hint.setVisibility(View.VISIBLE);
        String MESSAGE_HINT = "请稍后至订单详情页查看或重新收款";
        tv_hint.setText(MESSAGE_HINT);
        btn_receipt.setText("继续收款");
        if (PreferencesUtils.getBoolean(this, BaseConfigs.BOOLEAN_LOCAL_RECEIVABLES, true)) {
            if (XXPermissions.isHasPermission(this, Permission.READ_PHONE_STATE)&&SpeechUtilOffline.getInstance(CloseOrderActivity.this) != null) {
                OrderVoice orderVoice = new OrderVoice();
                orderVoice.setContent("收款结果未知");
                SpeechUtilOffline.getInstance(CloseOrderActivity.this).play(orderVoice, SpeechUtilOffline.PLAY_MODE.QUEUED);
            }
        }
    }

    private void setData(String Code, Response_Base response_base) {
        if (TextUtils.isEmpty(Code)) {
            Code = "";
        }
        btn_receipt.setVisibility(View.VISIBLE);
        iv_head.setImageResource(R.mipmap.casher_failure);
        iv_head.setVisibility(View.VISIBLE);
//        right_nav.setVisibility(View.VISIBLE);
        if ("1".equals(Code)) {
            tv_main_message.setText(FAIL_CLOSE_SUCCESS_MESSAGE);
            tv_hint.setVisibility(View.GONE);
            btn_receipt.setText("重新收款");
            if (XXPermissions.isHasPermission(this, Permission.READ_PHONE_STATE)&&SpeechUtilOffline.getInstance(getApplicationContext()) != null) {
                LogUtils.e("=== CloseOrderActivity play: 收款失败");
                OrderVoice orderVoice = new OrderVoice();
                orderVoice.setContent("收款失败");
                SpeechUtilOffline.getInstance(getApplicationContext()).play(orderVoice, SpeechUtilOffline.PLAY_MODE.QUEUED);
            }

            return;
        } else if ("2501".equals(Code)) {
            if (reset) {
                tv_main_message.setText(FAIL_MESSAGE);
                tv_hint.setVisibility(View.VISIBLE);
                tv_hint.setText(FAIL_MESSAGE_HINT);
                btn_receipt.setText("重新收款");
                if (XXPermissions.isHasPermission(this, Permission.READ_PHONE_STATE)&&SpeechUtilOffline.getInstance(CloseOrderActivity.this) != null) {
                    OrderVoice orderVoice = new OrderVoice();
                    orderVoice.setContent("收款结果未知");
                    SpeechUtilOffline.getInstance(CloseOrderActivity.this).play(orderVoice, SpeechUtilOffline.PLAY_MODE.QUEUED);
                }
            } else {
                tv_main_message.setText(FAIL_MESSAGE_RESET);
                tv_hint.setVisibility(View.GONE);
                right_nav.setVisibility(View.GONE);
                btn_receipt.setText("关单重试");
                if (XXPermissions.isHasPermission(this, Permission.READ_PHONE_STATE)&&SpeechUtilOffline.getInstance(CloseOrderActivity.this) != null) {
                    OrderVoice orderVoice = new OrderVoice();
                    orderVoice.setContent("关单失败 请重试");
                    SpeechUtilOffline.getInstance(CloseOrderActivity.this).play(orderVoice, SpeechUtilOffline.PLAY_MODE.QUEUED);
                }
            }
            return;
        } else if ("2502".equals(Code)) {
            iv_head.setImageResource(R.mipmap.casher_success);
            tv_main_message.setText(SUCCESS_MESSAGE);
            tv_hint.setVisibility(View.VISIBLE);
            tv_hint.setText(SUCCESS_MESSAGE_HINT);
            btn_receipt.setText("继续收款");
            if (response_base.getResultObject() != null) {
                Response_Pay response_pay = (Response_Pay) response_base.getResultObject();
//                request_pay.setReceiptAmount(response_pay.getReceiptAmount());
//                request_pay.setVoucherAmount(response_pay.getVoucherAmount());
//                request_pay.setTotalAmount(response_pay.getTotalAmount());
//                request_pay.setPayType(response_pay.getPayType());
//                request_pay.setOrderId(response_pay.getOrderId());
//                request_pay.setGooodsAmount(response_pay.getGooodsAmount());

//                if (!PayConfig.TYPE_ORDER_DISH.equals(response_pay.getOrderType())) {
//                    BasePresenter basePresenter = new BasePresenter(CloseOrderActivity.this);
//                    basePresenter.doPrinter(response_pay, null);
//                }

                /**
                 * 支付方式
                 */
                if (PayConfig.TYPE_PAY_CASH.equals(response_pay.getPayType())) {
                    str_voice_type = "现金";
                } else if (PayConfig.TYPE_PAY_ALIPAY.equals(response_pay.getPayType())) {
                    str_voice_type = "支付宝";
                } else if (PayConfig.TYPE_PAY_MEMBERCARD.equals(response_pay.getPayType())) {
                    str_voice_type = "会员卡";
                } else if (PayConfig.TYPE_PAY_UNION.equals(response_pay.getPayType())) {
                    str_voice_type = "银联";
                } else if (PayConfig.TYPE_PAY_WEIXIN.equals(response_pay.getPayType())) {
                    str_voice_type = "微信支付";
                } else if (PayConfig.TYPE_PAY_YUNSHANFU.equals(response_pay.getPayType())) {
                    str_voice_type = "云闪付";
                }
                String totalAmountStr = Tools.getSafeString(response_pay.getTotalAmount(), "0.00");
                /**
                 * 语音播报支付方式+收款成功+xx.xx元
                 */
                if ("商品核销".equals(verifyCode)) {
                    if (XXPermissions.isHasPermission(this, Permission.READ_PHONE_STATE)&&SpeechUtilOffline.getInstance(CloseOrderActivity.this) != null) {
                        OrderVoice orderVoice = new OrderVoice();
                        orderVoice.setContent("口碑商品券核销成功");
                        SpeechUtilOffline.getInstance(CloseOrderActivity.this).play(orderVoice, SpeechUtilOffline.PLAY_MODE.QUEUED);
                    }
                } else {
                    try {
                        if (XXPermissions.isHasPermission(this, Permission.READ_PHONE_STATE)&&SpeechUtilOffline.getInstance(getApplicationContext()) != null && !PayConfig.TYPE_ORDER_CANCEL.equals(response_pay.getOrderType())) {
                            String playVoice = str_voice_type + "收款成功" + totalAmountStr + "元";
                            LogUtils.e("=== CloseOrderActivity play: " + playVoice);
                            OrderVoice orderVoice = new OrderVoice();
                            orderVoice.setContent(playVoice);
                            SpeechUtilOffline.getInstance(getApplicationContext()).play(orderVoice, SpeechUtilOffline.PLAY_MODE.QUEUED);
                        }
                    } catch (Exception e) {
                        LogUtils.i(e.toString());
                    }
                }
            }
            return;
        } else if ("2503".equals(Code)) {
            tv_main_message.setText(FAIL_MESSAGE);
            tv_hint.setVisibility(View.VISIBLE);
            tv_hint.setText(FAIL_MESSAGE_HINT);
            btn_receipt.setText("重新收款");
            if (XXPermissions.isHasPermission(this, Permission.READ_PHONE_STATE)&&SpeechUtilOffline.getInstance(CloseOrderActivity.this) != null) {
                OrderVoice orderVoice = new OrderVoice();
                orderVoice.setContent("收款结果未知");
                SpeechUtilOffline.getInstance(CloseOrderActivity.this).play(orderVoice, SpeechUtilOffline.PLAY_MODE.QUEUED);
            }
            return;
        } else {

            tv_main_message.setText(FAIL_MESSAGE);
            tv_hint.setVisibility(View.VISIBLE);
            String MESSAGE_HINT = "1.请确认手机端支付结果\n2.检查网络情况是否正常\n3.请重新收款";
            tv_hint.setText(FAIL_MESSAGE_HINT);
            btn_receipt.setText("重新收款");
            if (XXPermissions.isHasPermission(this, Permission.READ_PHONE_STATE)&&SpeechUtilOffline.getInstance(CloseOrderActivity.this) != null) {
                OrderVoice orderVoice = new OrderVoice();
                orderVoice.setContent("收款结果未知");
                SpeechUtilOffline.getInstance(CloseOrderActivity.this).play(orderVoice, SpeechUtilOffline.PLAY_MODE.QUEUED);
            }
        }
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.btn_receipt) {
            if ("关单重试".equals(btn_receipt.getText())) {
                reset = true;
                closeOrder();
            } else if ("重新收款".equals(btn_receipt.getText())) {
                RxBus.getInstance().send(Events.PAY_COMPETE_TO_CLOSE, Events.PAY_COMPETE_TO_CLOSE);
                Intent intent = new Intent(CloseOrderActivity.this, CashierActivity.class);
                intent.putExtra(PayConfig.INTENT_ORDER_REPAY, request_pay.getTotalAmount());
                startActivity(intent);
                finish();
            } else {
                RxBus.getInstance().send(Events.PAY_COMPETE_TO_CLOSE, Events.PAY_COMPETE_TO_CLOSE);
                Intent intent = new Intent(CloseOrderActivity.this, CashierActivity.class);
                startActivity(intent);
                finish();
            }
        } else if (i == R.id.right_nav) {
            RxBus.getInstance().send(Events.PAY_COMPETE_TO_CLOSE, Events.PAY_COMPETE_TO_CLOSE);
            finish();
        } else if (i == R.id.back_nav) {
            RxBus.getInstance().send(Events.PAY_COMPETE_TO_CLOSE, Events.PAY_COMPETE_TO_CLOSE);
            Intent intent = new Intent(CloseOrderActivity.this, CashierActivity.class);
            startActivity(intent);
            finish();
        }
    }


    //禁用物理返回键

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            RxBus.getInstance().send(Events.PAY_COMPETE_TO_CLOSE, Events.PAY_COMPETE_TO_CLOSE);
            Intent intent = new Intent(CloseOrderActivity.this, CashierActivity.class);
            startActivity(intent);
            finish();
            return true;
        }
        return false;
    }
}
